import { Component, Fragment, h, Element, Watch, Prop, State } from '@stencil/core';
import { mapStyleToElement } from '../../utils/utils';

const TOTAL_WIDTH = document.documentElement.offsetWidth / 3;
const DEFAULT_COUNT = 4;
const ITEM_FACTOR = TOTAL_WIDTH / DEFAULT_COUNT;
const HEIGHT = 40;

@Component({
  tag: 't-nav',
  styleUrl: 't-nav.scss',
  shadow: true,
})
export class TPageLoading {
  @State() index = -1;
  @State() liWidth = 0;
  @State() slide = false;

  @Element() slot;
  @Prop() data;
  @Prop() width: number;

  renderHiddenMenu() {
    return (
      this.data[this.index]?.children && (
        <div class="hidden-menu animate-all" style={{ width: `${TOTAL_WIDTH / 2}px`, left: `${this.index * ITEM_FACTOR}px` }}>
          {this.data[this.index]?.children?.map(child => (
            <div>{child.label}</div>
          ))}
        </div>
      )
    );
  }

  renderNav() {
    return this.data?.map((d, index) => {
      return (
        <Fragment>
          <li
            id={`t-li-${index}`}
            onMouseEnter={() => {
              this.index = index;
              this.slide = true;
            }}
            onMouseLeave={() => {
              this.index = -1;
              this.slide = false;
            }}
            class="flex justify-center items-center"
            style={{ minWidth: `${ITEM_FACTOR}px`, height: `${HEIGHT}px` }}
          >
            {d.label}
          </li>
        </Fragment>
      );
    });
  }

  componentWillLoad() {
    this.parseMyArrayProp(this.data);
  }

  @Watch('data')
  parseMyArrayProp(newValue: string) {
    try {
      if (newValue) this.data = JSON.parse(newValue);
    } catch (error) {}
  }

  renderSpecialEffect() {
    return <div class="cover animate-all" style={{ width: `${this.liWidth}px`, left: `${this.index * ITEM_FACTOR}px` }} />;
  }

  componentDidRender() {
    mapStyleToElement(this, '.relative')
    if(this.index !== -1) this.liWidth = this.slot.shadowRoot.querySelector(`#t-li-${this.index}`).clientWidth;
  }

  render() {
    return (
      <div class={`relative`}>
        <ul class="flex wrapper" style={{ width: `${this.width}px` }}>
          {this.renderSpecialEffect()}
          {this.renderNav()}
        </ul>
        {this.renderHiddenMenu()}
      </div>
    );
  }
}
